using UnityEngine;

public class Train : MonoBehaviour
{
    public float speed = 5f;  // 最大移动速度
    public float accelerationTime = 2f;  // 从0加速到最大速度需要的时间
    public float decelerationTime = 1.5f;  // 从最大速度减速到0需要的时间
    
    private float currentSpeed = 0f;  // 当前实际速度
    public TrackPoint currentPoint;  // 当前轨道点
    private TrackPoint nextPoint;    // 下一个轨道点
    private Vector3 moveDirection;    // 实际移动方向
    private bool isMoving = false;   // 是否在移动
    
    private void Start()
    {
        if (currentPoint == null)
        {
            Debug.LogError("Train needs a starting track point!");
            return;
        }
        
        // 初始位置设置在当前轨道点
        transform.position = currentPoint.transform.position;
        moveDirection = Vector3.zero;
        isMoving = false;
        nextPoint = null;  // 等待输入来决定下一个点
    }

    private void Update()
    {
        if (nextPoint == null) return;

        // 更新速度
        if (isMoving)
        {
            // 加速
            currentSpeed = Mathf.MoveTowards(currentSpeed, speed, speed * Time.deltaTime / accelerationTime);
        }
        else
        {
            // 减速
            currentSpeed = Mathf.MoveTowards(currentSpeed, 0, speed * Time.deltaTime / decelerationTime);
        }

        // 只有有速度时才移动
        if (currentSpeed > 0)
        {
            // 移动火车
            float step = currentSpeed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, nextPoint.transform.position, step);

            // 平滑转向移动方向
            if (moveDirection != Vector3.zero)
            {
                Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, step * 2);
            }

            // 检查是否到达下一个轨道点
            if (Vector3.Distance(transform.position, nextPoint.transform.position) < 0.1f)
            {
                // 更新当前点
                currentPoint = nextPoint;
                transform.position = currentPoint.transform.position; // 确保精确位置
                nextPoint = null;
                moveDirection = Vector3.zero;
                isMoving = false;
            }
        }
    }

    // 紧急制动方法
    public void EmergencyBrake()
    {
        currentSpeed = 0f;
        isMoving = false;
    }

    // 根据输入方向选择下一个轨道点
    [SerializeField]
    private float directionThreshold = 0.6f; // 选择方向需要的最小输入量
    
    public void SetDirection(Vector2 inputDir)
    {
        // 如果已经在移动或没有当前点，则忽略输入
        if (currentPoint == null || isMoving) return;
        
        // 如果输入太小，忽略它
        if (inputDir.magnitude < 0.1f) return;

        // 将2D输入方向转换为3D方向
        Vector3 direction = new Vector3(inputDir.x, 0, inputDir.y);
        
        // 不允许后退（如果火车已经有了前进方向）
        if (moveDirection != Vector3.zero)
        {
            float forwardAngle = Vector3.Angle(moveDirection, direction);
            if (forwardAngle > 90f) return;
        }
        
        // 遍历所有可能的下一个点
        TrackPoint bestPoint = null;
        float bestMatchValue = -1f;
        
        foreach (var point in currentPoint.nextPoints)
        {
            if (point == null || point == currentPoint) continue;
            
            // 计算到该点的方向
            Vector3 pointDirection = (point.transform.position - transform.position).normalized;
            
            // 计算方向匹配度（点积）
            float directionMatch = Vector3.Dot(direction, pointDirection);
            
            // 只有当输入方向足够接近某个路径方向，并且输入强度足够大时才选择该方向
            if (directionMatch > bestMatchValue && directionMatch > 0.5f && inputDir.magnitude > directionThreshold)
            {
                bestMatchValue = directionMatch;
                bestPoint = point;
            }
        }
        
        // 如果找到合适的点，就设置为下一个目标
        if (bestPoint != null)
        {
            nextPoint = bestPoint;
            moveDirection = (nextPoint.transform.position - transform.position).normalized;
            isMoving = true;
        }
    }
}